package com.myTest.config;

import com.myTest.pojo.Configuration;
import com.myTest.pojo.MappedStatement;
import com.myTest.pojo.SqlType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void paresConfig(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");
        //获取所有节点
        List<Element> elements = rootElement.elements();
        if(elements!=null&&elements.size()>0){
            for (Element element : elements) {
                String nodeName = element.getName();
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String paramterType = element.attributeValue("paramterType");
                String sqlText = element.getTextTrim();
                MappedStatement mappedStatement = new MappedStatement();
                //设置节点类型（大写）：select、insert、update、delete
                mappedStatement.setSqlType(SqlType.valueOf(nodeName.toUpperCase()));
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParamterType(paramterType);
                mappedStatement.setSql(sqlText);
                //key为mapper对象的namespace和select对象的属性id
                String key = namespace+"."+id;
                configuration.getMappedStatementMap().put(key,mappedStatement);
            }
        }

        /*String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            //key为mapper对象的namespace和select对象的属性id
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }*/
    }
}
